package org.jeecg.modules.messages.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.messages.entity.BlogMessages;
import org.jeecg.modules.messages.service.BlogMessagesService;
import org.jeecg.modules.messageReplies.entity.BlogMessageReplies;
import org.jeecg.modules.messageReplies.service.BlogMessageRepliesService;
import org.jeecg.config.shiro.IgnoreAuth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: blog_messages
 * @Author: jeecg-boot
 * @Date: 2025-06-30
 * @Version: V1.0
 */
@Tag(name = "blog_messages")
@RestController
@RequestMapping("/blog/messages")
@Slf4j
public class BlogMessagesController extends JeecgController<BlogMessages, BlogMessagesService> {
    @Autowired
    private BlogMessagesService blogMessagesService;
    
    @Autowired
    private BlogMessageRepliesService blogMessageRepliesService;

    /**
     * 分页列表查询
     *
     * @param blogMessages
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "blog_messages-分页列表查询")
    @Operation(summary = "blog_messages-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BlogMessages>> queryPageList(BlogMessages blogMessages,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<BlogMessages> queryWrapper = QueryGenerator.initQueryWrapper(blogMessages, req.getParameterMap());
        Page<BlogMessages> page = new Page<BlogMessages>(pageNo, pageSize);
        IPage<BlogMessages> pageList = blogMessagesService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 公开的留言列表查询（无需权限）
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Operation(summary = "公开的留言列表查询")
    @GetMapping(value = "/public/list")
    @IgnoreAuth
    public Result<IPage<BlogMessages>> getPublicMessages(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<BlogMessages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询已审核的留言
                .eq("parent_id", "0") // 只查询顶级留言
                .orderByDesc("create_time");
        Page<BlogMessages> page = new Page<BlogMessages>(pageNo, pageSize);
        IPage<BlogMessages> pageList = blogMessagesService.page(page, queryWrapper);
        
        // 为每个留言加载回复
        for (BlogMessages message : pageList.getRecords()) {
            try {
                List<BlogMessageReplies> replies = blogMessagesService.getRepliesByMessageId(message.getId());
            
            // 将BlogMessageReplies转换为BlogMessages格式，以便前端兼容
            List<BlogMessages> convertedReplies = replies.stream().map(reply -> {
                BlogMessages convertedReply = new BlogMessages();
                convertedReply.setId(reply.getId());
                convertedReply.setNickname(reply.getNickname());
                convertedReply.setEmail(reply.getEmail());
                convertedReply.setContent(reply.getContent());
                convertedReply.setCreateTime(reply.getCreateTime());
                convertedReply.setLikeCount(reply.getLikeCount());
                convertedReply.setIsAdminReply(reply.getIsAdminReply());
                
                // 设置前端需要的时间字段
                convertedReply.setCreateTime(reply.getCreateTime());
                
                // 设置头像颜色（前端需要）
                String nickname = reply.getNickname();
                if (nickname != null && !nickname.isEmpty()) {
                    String avatarColor = generateAvatarColor(nickname);
                    convertedReply.setAvatarColor(avatarColor);
                }
                
                return convertedReply;
            }).collect(Collectors.toList());
            message.setReplies(convertedReplies);
            } catch (Exception e) {
                log.error("加载留言 {} 的回复时发生错误", message.getId(), e);
                message.setReplies(new ArrayList<>());
            }
        }
        
        return Result.OK(pageList);
    }

    /**
     * 公开的留言添加（无需权限）
     *
     * @param blogMessages
     * @param request
     * @return
     */
    @Operation(summary = "公开的留言添加")
    @PostMapping(value = "/public/add")
    @IgnoreAuth
    public Result<String> addPublicMessage(@RequestBody BlogMessages blogMessages, HttpServletRequest request) {
        // 设置默认状态为待审核
        blogMessages.setStatus(0);
        // 设置父留言ID为0（顶级留言）
        blogMessages.setParentId("0");
        // 设置IP地址
        blogMessages.setIpAddress(getClientIpAddress(request));
        // 设置用户代理
        blogMessages.setUserAgent(request.getHeader("User-Agent"));
        // 设置创建时间
        blogMessages.setCreateTime(new Date());
        blogMessagesService.save(blogMessages);
        return Result.OK("留言提交成功，等待审核！");
    }

    /**
     * 公开的留言回复（无需权限）
     *
     * @param blogMessages
     * @param request
     * @return
     */
    @Operation(summary = "公开的留言回复")
    @PostMapping(value = "/public/reply")
    @IgnoreAuth
    public Result<String> replyPublicMessage(@RequestBody BlogMessages blogMessages, HttpServletRequest request) {
        // 创建回复对象
        BlogMessageReplies reply = new BlogMessageReplies();
        reply.setMessageId(blogMessages.getParentId()); // 使用parentId作为messageId
        reply.setNickname(blogMessages.getNickname());
        reply.setEmail(blogMessages.getEmail());
        reply.setContent(blogMessages.getContent());
        reply.setStatus(0); // 待审核
        reply.setIpAddress(getClientIpAddress(request));
        reply.setUserAgent(request.getHeader("User-Agent"));
        reply.setCreateTime(new Date());
        
        // 保存回复到blog_message_replies表
        blogMessageRepliesService.save(reply);
        
        // 更新原留言的回复数量
        if (blogMessages.getParentId() != null && !blogMessages.getParentId().equals("0")) {
            BlogMessages parentMessage = blogMessagesService.getById(blogMessages.getParentId());
            if (parentMessage != null) {
                parentMessage.setReplyCount(parentMessage.getReplyCount() != null ? parentMessage.getReplyCount() + 1 : 1);
                blogMessagesService.updateById(parentMessage);
            }
        }
        
        return Result.OK("回复提交成功，等待审核！");
    }

    /**
     * 公开的留言点赞（无需权限）
     *
     * @param id
     * @return
     */
    @Operation(summary = "公开的留言点赞")
    @PostMapping(value = "/public/like")
    @IgnoreAuth
    public Result<String> likeMessage(@RequestParam(name = "id", required = true) String id) {
        BlogMessages message = blogMessagesService.getById(id);
        if (message == null) {
            return Result.error("留言不存在");
        }
        // 增加点赞数
        message.setLikeCount(message.getLikeCount() != null ? message.getLikeCount() + 1 : 1);
        blogMessagesService.updateById(message);
        return Result.OK("点赞成功！");
    }

    /**
     * 获取留言统计（无需权限）
     *
     * @return
     */
    @Operation(summary = "获取留言统计")
    @GetMapping(value = "/public/stats")
    @IgnoreAuth
    public Result<?> getMessageStats() {
        QueryWrapper<BlogMessages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只统计已审核的留言

        // 总留言数
        long totalMessages = blogMessagesService.count(queryWrapper);

        // 参与用户数（去重昵称）
        long uniqueUsers = blogMessagesService.count(queryWrapper.select("DISTINCT nickname"));

        // 今日留言数
        QueryWrapper<BlogMessages> todayWrapper = new QueryWrapper<>();
        todayWrapper.eq("status", 1)
                .ge("create_time", LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0));
        long todayMessages = blogMessagesService.count(todayWrapper);

        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("totalMessages", totalMessages);
        stats.put("uniqueUsers", uniqueUsers);
        stats.put("todayMessages", todayMessages);

        return Result.OK(stats);
    }

    /**
     * 添加
     *
     * @param blogMessages
     * @return
     */
    @AutoLog(value = "blog_messages-添加")
    @Operation(summary = "blog_messages-添加")
    @RequiresPermissions("messages:blog_messages:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BlogMessages blogMessages) {
        blogMessagesService.save(blogMessages);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param blogMessages
     * @return
     */
    @AutoLog(value = "blog_messages-编辑")
    @Operation(summary = "blog_messages-编辑")
    @RequiresPermissions("messages:blog_messages:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BlogMessages blogMessages) {
        blogMessagesService.updateById(blogMessages);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "blog_messages-通过id删除")
    @Operation(summary = "blog_messages-通过id删除")
    @RequiresPermissions("messages:blog_messages:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        blogMessagesService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "blog_messages-批量删除")
    @Operation(summary = "blog_messages-批量删除")
    @RequiresPermissions("messages:blog_messages:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.blogMessagesService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "blog_messages-通过id查询")
    @Operation(summary = "blog_messages-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BlogMessages> queryById(@RequestParam(name = "id", required = true) String id) {
        BlogMessages blogMessages = blogMessagesService.getById(id);
        if (blogMessages == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(blogMessages);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param blogMessages
     */
    @RequiresPermissions("messages:blog_messages:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BlogMessages blogMessages) {
        return super.exportXls(request, blogMessages, BlogMessages.class, "blog_messages");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("messages:blog_messages:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BlogMessages.class);
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xip = request.getHeader("X-Real-IP");
        String xfor = request.getHeader("X-Forwarded-For");
        if (xfor != null && !xfor.isEmpty() && !"unKnown".equalsIgnoreCase(xfor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xfor.indexOf(",");
            if (index != -1) {
                return xfor.substring(0, index);
            } else {
                return xfor;
            }
        }
        xfor = xip;
        if (xfor != null && !xfor.isEmpty() && !"unKnown".equalsIgnoreCase(xfor)) {
            return xfor;
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getRemoteAddr();
        }
        return xfor;
    }

    /**
     * 根据昵称生成头像颜色
     */
    private String generateAvatarColor(String nickname) {
        if (nickname == null || nickname.isEmpty()) {
            return "#1890ff";
        }
        
        // 使用昵称的hashCode来生成固定的颜色
        int hashCode = nickname.hashCode();
        String[] colors = {
            "#1890ff", "#52c41a", "#faad14", "#f5222d", "#722ed1",
            "#13c2c2", "#eb2f96", "#fa8c16", "#a0d911", "#2f54eb"
        };
        
        int colorIndex = Math.abs(hashCode) % colors.length;
        return colors[colorIndex];
    }
}
